<template>
    <div class="issue">
        <div class="upload">
            <div class="img-box" v-for="(item, index) in imgList" :key="index">
                <image class="img" :src="item.pic" mode="aspectFill" @tap="lookImages(index)"/>
                <image class="delete" src="http://common.static.sangeayi.cn/shop_wx/images/icon_good_delete1.png" @tap="deleteImg(item.pic, item._id)"/>
            </div>
            <div class="add" @tap="upload">
                <image src="../../static/images/add.png"/>
            </div>
        </div>
        <!-- <button class="send" @tap="sendIssue">存储到数据库</button> -->
        <div class="loading-container" v-if="!getSrcFlag">
            <loading></loading>
        </div>
    </div>
</template>

<script>
import tools from 'common/js/tools'
import Loading from 'components/loading'
export default {
  data () {
    return {
      desc: '',
      openId: '',
      imgUrl: '',
      name: '',
      head: '',
      fileID: '',
      imgList: [],
      getSrcFlag: false
    }
  },

  components: {
    Loading
  },

  onShow () {
    const that = this
    that.getOpenId()
  },

  computed: {
    picList () {
      const that = this
      if (that.imgList && that.imgList.length > 0) {
        let arr = []
        that.imgList.forEach(item => {
          arr.push(item.pic)
        })
        return arr
      }
      return []
    }
  },

  methods: {
    upload () {
      const that = this
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          wx.showLoading({
            title: '上传中'
          })
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          let filePath = res.tempFilePaths[0]
          const name = Math.random() * 1000000
          const cloudPath = 'picture/' + name + filePath.match(/\.[^.]+?$/)[0]
          console.log(name, filePath.match(/\.[^.]+?$/), cloudPath)
          wx.cloud.uploadFile({
            cloudPath, // 云存储图片名字
            filePath // 临时路径
          }).then(res => {
            console.log('[上传图片] 成功：', res)
            wx.hideLoading()
            that.imgUrl = res.fileID
            const db = wx.cloud.database()
            db.collection('image').add({
              data: {
                pic: that.imgUrl,
                time: db.serverDate()
              }
            }).then(res => {
              tools.showToast('存储照片成功')
              that.getList()
            }).catch(e => {
              tools.showToast('存储照片失败')
            })
          }).catch(e => {
            console.log('[上传图片] 失败：', e)
          })
        }
      })
    },

    getOpenId () {
      const that = this
      wx.cloud.callFunction({
        name: 'user',
        data: {}
      }).then(res => {
        that.openId = res.result.openid
        that.getList()
      })
    },
    getList () {
      const that = this
      wx.cloud.callFunction({
        name: 'imageList',
        data: {
          '_openid': that.openId
        }
      }).then(res => {
        console.log(res)
        that.imgList = res.result.data.reverse()
        that.getSrcFlag = true
      }).catch(err => {
        console.log(err)
        that.imgList = []
        that.getSrcFlag = true
      })
    },

    deleteImg (img, id) {
      const that = this
      wx.cloud.deleteFile({
        fileList: [img]
      }).then(res => {
        // handle success
        const db = wx.cloud.database()
        db.collection('image').doc(id).remove().then(res => {
          console.log(res)
          console.log('[删除图片] 成功')
          that.getList()
        }).catch(err => {
          console.log(err)
        })
      }).catch(e => {
        console.log('[删除图片] 失败', e)
        // handle error
      })
    },

    lookImages (index) {
      let that = this
      wx.previewImage({
        current: that.picList[index],
        urls: that.picList // 需要预览的图片http链接列表
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
.loading-container
    position fixed
    width 100%
    height 100%
    top 0
    bottom 0
    left 0
    right 0
    background #fff
    margin auto
    display flex
    justify-content center
    align-items center
.issue
    padding 0 30rpx
    .upload
        display flex
        justify-content flex-start
        align-items flex-start
        flex-wrap wrap
        padding 30rpx 0
        .add
            height 220rpx
            width 220rpx
            background #E5e5e5
            display flex
            justify-content center
            align-items center
            image
                width 50rpx
                height 50rpx
        .img-box
            height 220rpx
            width 220rpx
            position relative
            margin 0 15rpx 20rpx 0
            &:nth-of-type(3n+0)
                margin 0 0 20rpx 0
            .img
                height 100%
                width 100%
            .delete
                position absolute
                right -12rpx
                top -12rpx
                height 40rpx
                width 40rpx
                border-radius 50%
                z-index 99
                cursor pointer
                background #fff
    .send
        background #ED695D
        color #fff
</style>
